package com.igoal.dao;

import java.util.List;

import javax.persistence.Table;

import org.hibernate.Query;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import com.igoal.entity.User;
import com.igoal.web.Constants;

@Repository("userDaoExt")
public class UserDAOExtImpl extends GenericDaoHibernate<User, Long> implements
		UserDAOExt {

	public UserDAOExtImpl() {
		super(User.class);
	}

	/**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<User> getUsers() {
        return getHibernateTemplate().find("from User u order by upper(u.username)");
    }

    /**
     * {@inheritDoc}
     */
    public User saveUser(User user) {
        if (log.isDebugEnabled())
            log.debug("user's id: " + user.getId());
        getHibernateTemplate().saveOrUpdate(user);
        // necessary to throw a DataIntegrityViolation and catch it in UserManager
        getHibernateTemplate().flush();
        return user;
    }

    /**
     * Overridden simply to call the saveUser method. This is happenening 
     * because saveUser flushes the session and saveObject of BaseDaoHibernate 
     * does not.
     *
     * @param user the user to save
     * @return the modified user (with a primary key set if they're new)
     */
    @Override
    public User save(User user) {
        return this.saveUser(user);
    }

    /** 
     * {@inheritDoc}
    */
    @SuppressWarnings("rawtypes")
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List users = getHibernateTemplate().find("from User where username=?", username);
        if (users == null || users.isEmpty()) {
            throw new UsernameNotFoundException("user '" + username + "' not found...");
        } else {
            return (UserDetails) users.get(0);
        }
    }

    /** 
     * {@inheritDoc}
    */
    public String getUserPassword(String username) {
        SimpleJdbcTemplate jdbcTemplate =
                new SimpleJdbcTemplate(SessionFactoryUtils.getDataSource(getSessionFactory()));
        Table table = AnnotationUtils.findAnnotation(User.class, Table.class);
        return jdbcTemplate.queryForObject(
                "select password from " + table.name() + " where username=?", String.class, username);

    }

	public boolean existsEmail(String email) {
		List users = getHibernateTemplate().find("from User where email=?", email);
		return !users.isEmpty();
	}

	public boolean existsUsername(String username) {
		List users = getHibernateTemplate().find("from User where username=?", username);
		return !users.isEmpty();
	}
	
	public List<User> searchUsers(String text, int page, String ignoreUserName){
		return searchUsers(text, page, Constants.MAX_SEARCH_RESULT, ignoreUserName);
	}
	
	public List<User> searchUsers(String text, int page, int maxResultPerPage, String ignoreUserName){
		String likeText = "like :cri";
		StringBuffer queryBuffer = new StringBuffer();
		queryBuffer.append("Select distinct(u) from User u ");
		queryBuffer.append("where u.accountLocked=false and username != :ignoreUserName "); 
		queryBuffer.append("and ((u.username "+likeText+") or (u.email "+likeText+") ");
		queryBuffer.append("or (u.userInfo.firstName "+likeText+") or (u.userInfo.middleName "+likeText+") or (u.userInfo.lastName "+likeText+") ");
		queryBuffer.append("or (u.userInfo.yahoo "+likeText+") or (u.userInfo.skype "+likeText+") or (u.userInfo.facebook "+likeText+") ");
		queryBuffer.append("or (u.userInfo.aboutMe "+likeText+") or (u.userInfo.website "+likeText+"))");

		Query query = getSession().createQuery(queryBuffer.toString());
		query.setString("cri", "%"+text+"%");
		query.setString("ignoreUserName", ignoreUserName);
		
		if(maxResultPerPage > 0){
			query.setMaxResults(maxResultPerPage);
		}
		if(page >= 0){			
			query.setFirstResult(page * maxResultPerPage);
		}
		List<User> users = query.list();
		return users;
	}
	
	public List<User> searchUsers(String text, int page){
		return searchUsers(text, page, Constants.MAX_SEARCH_RESULT);
	}
	
	public List<User> searchUsers(String text, int page, int maxResultPerPage) {
		String likeText = "like :cri";
		StringBuffer queryBuffer = new StringBuffer();
		queryBuffer.append("Select distinct(u) from User u ");
		queryBuffer.append("where u.accountLocked=false "); 
		queryBuffer.append("and ((u.username "+likeText+") or (u.email "+likeText+") ");
		queryBuffer.append("or (u.userInfo.firstName "+likeText+") or (u.userInfo.middleName "+likeText+") or (u.userInfo.lastName "+likeText+") ");
		queryBuffer.append("or (u.userInfo.yahoo "+likeText+") or (u.userInfo.skype "+likeText+") or (u.userInfo.facebook "+likeText+") ");
		queryBuffer.append("or (u.userInfo.aboutMe "+likeText+") or (u.userInfo.website "+likeText+"))");

		Query query = getSession().createQuery(queryBuffer.toString());
		query.setString("cri", "%"+text+"%");
		if(maxResultPerPage > 0){
			query.setMaxResults(maxResultPerPage);
		}
		if(page >= 0){			
			query.setFirstResult(page * maxResultPerPage);
		}
		List<User> users = query.list();
		return users;
	}
	
//	public List<User> searchUsers(String text, int page) {
//		DetachedCriteria dc = DetachedCriteria.forClass(User.class);
//		dc.add(Restrictions.or(Restrictions.like("username", text, MatchMode.ANYWHERE), 
//				Restrictions.or(Restrictions.like("email", text, MatchMode.ANYWHERE),
////				Restrictions.or(Restrictions.like("userInfo.firstName", text, MatchMode.ANYWHERE), 
//				Restrictions.or(Restrictions.like("userInfo.middleName", text, MatchMode.ANYWHERE), 
//				Restrictions.or(Restrictions.like("userInfo.lastName", text, MatchMode.ANYWHERE), 
//				Restrictions.or(Restrictions.like("userInfo.yahoo", text, MatchMode.ANYWHERE), 
//				Restrictions.or(Restrictions.like("userInfo.skype", text, MatchMode.ANYWHERE), 
//				Restrictions.or(Restrictions.like("userInfo.facebook", text, MatchMode.ANYWHERE),
//				Restrictions.or(Restrictions.like("userInfo.aboutMe", text, MatchMode.ANYWHERE), 
//				Restrictions.like("userInfo.website", text, MatchMode.ANYWHERE))))))))));
//		dc.add(Restrictions.eq("accountLocked", false));
//		
//		List<User> result = findByCriteria(dc, page*WebPreferences.MAX_SEARCH_RESULT, WebPreferences.MAX_SEARCH_RESULT);
//		
//		return result;
//	}
	
	public boolean hasSearchResult(String text, int page) {
		List result = searchUsers(text, page);
		return result.size() > 0;
	}
	
	public int countSearchResult(String text){
		List result = searchUsers(text, -1, -1);
		return result.size();
	}
	
	public boolean hasSearchResult(String text, int page, String ignoreUserName) {
		List result = searchUsers(text, page, Constants.MAX_SEARCH_RESULT, ignoreUserName);
		return result.size() > 0;
	}
	
	public int countSearchResult(String text, String ignoreUserName){
		List result = searchUsers(text, -1, -1, ignoreUserName);
		return result.size();
	}
}
